<?php
use Facebook\FacebookSession;
use Facebook\FacebookRequestException;
use Facebook\FacebookRequest;
require ('facebook/php-sdk-v4/autoload.php');
class FacebookPost extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		$this->load->database ();
		$this->load->helper ( "url" );
		$this->config->load ( 'config' );
	}
	public function index() {
		session_start ();
		if (strcmp ( $_SESSION ["userName"], "Anonymous" ) == 0) {
			redirect ( base_url ( "index.php/FacebookLogin/FacebookLogin/index" ) );
		} else {
			$userId = $_SESSION ["userId"];
			$funcType = $_REQUEST ["funcType"];
			$imageName = $_SESSION ["imageName"];
			$imageUpload = "";
			//
			// If you're making app-level requests:
			switch ($funcType) {
				case 0 :
					$imageUpload = $_SESSION ["watermarkPath"];
					break;
				case 1 :
					$imageUpload = $_SESSION ["twoImagesPath"];
					break;
				case 2 :
					$imageUpload = $_SESSION ["framePath"];
					break;
				case 3 :
					$imageUpload = $_SESSION ["cartoonPath"];
					break;
				case 4 :
					$imageUpload = "";
					break;
				case 5 :
					$imageUpload = $_SESSION ["funnyEffectPath"];
					break;
				case 6 : 
					$imageUpload = $_SESSION ["sketchPath"];
					break;
			}
			$data ["imageUploadPath"] = $imageUpload;
			$data ["access_token"] = $_SESSION ["access_token"];
			//
			try {
				$publish_permission = $_SESSION ["publish_permission"];
				// if publish_actions is granted
				if (strcmp ( $publish_permission, "granted" ) == 0) {
					// Get user's friend
					$this->load->Model ( "muser" );
					$friendList = $this->muser->getUserFriends ( $userId );
					$friendLists = $this->muser->getUserFriendLists($userId);
					// Pass friendList to data
					$friendList = ( array ) $friendList [0];
					$friendList = $friendList ["Friends"];
					$data ["friendList"] = $friendList;
					// Pass friendLists to data
					$friendLists = (array)$friendLists[0];
					$friendLists = $friendLists["FriendLists"];
					
					$data["friendLists"] = $friendLists;
					// var_dump($friendList);
					// Try to post one status then get the granted permission
				} else {
					// In case user declined to grant the permission
				}
			} catch ( FacebookRequestException $ex ) {
				// Session not valid, Graph API returned an exception with the reason.
				echo "FacebookRequestException " . $ex->getMessage ();
			} catch ( \Exception $ex ) {
				// Graph API returned info, but it may mismatch the current app or have expired.
				echo "OtherException " . $ex->getMessage ();
			}
			// Pass friendlist to $data
			$data ["funcType"] = $funcType;
			//
			// var_dump(json_encode($friendList));
			
			switch ($_SESSION ["privacyValue"]) {
				case "EVERYONE" :
					$nodeString = "[{name: '" . $_SESSION ['userName'] . "', description: '', id: '', group: 0}, ".substr ( $friendLists, 1, strlen ( $friendLists ) - 2).", {name: 'public users', description: '', id: '', group: 3}]" ;
					$data ["onloadNodes"] = $nodeString;
					$numLists = substr_count ( $nodeString, "{" ) - 1;
					$onloadLinks = "[";
					for($i = 1; $i < $numLists + 1; $i ++) {
						$onloadLinks = $onloadLinks . "{source: $i, target: 0, value: 20}, ";
						if ($i == $numLists)
							$onloadLinks = $onloadLinks . "{source: $i, target: 0, value: 40}";
					}
					$onloadLinks = $onloadLinks . "]";
					// var_dump($nodeString);
					$data ["onloadLinks"] = $onloadLinks;
					break;
				case "ALL_FRIENDS" :
					$nodeString = "[{name: '" . $_SESSION ['userName'] . "', description: '', id: '', group: 0}, ".substr ( $friendLists, 1, strlen ( $friendLists )) ;
					$data ["onloadNodes"] = $nodeString;
					$numLists = substr_count ( $nodeString, "{" ) - 1;
					$onloadLinks = "[";
					for($i = 1; $i < $numLists + 1; $i ++) {
						$onloadLinks = $onloadLinks . "{source: $i, target: 0, value: 20}, ";
						if ($i == $numLists)
							$onloadLinks = $onloadLinks . "{source: $i, target: 0, value: 20}";
					}
					$onloadLinks = $onloadLinks . "]";
					// var_dump($nodeString);
					$data ["onloadLinks"] = $onloadLinks;
					break;
				case "SELF" :
				default :
					$data ["onloadNodes"] = "[{name: '" . $_SESSION ['userName'] . "', description: '', id: '', group: 0}]";
					$data ["onloadLinks"] = "[]";
					break;
			}
			$this->load->view ( "FacebookPost/index", $data );
		}
	}
	public function process() {
		$funcType = $_REQUEST ["funcType"];
		var_dump ( $_POST );
		if (isset ( $_POST )) {
			// var_dump($_POST);
			session_start ();
			$imagePath = $_POST ["imagePath"];
			$message = $_POST ["message"];
			$userId = $_SESSION ["userId"];
			// echo $message;
			$appId = $this->config->item ( 'AppId' );
			$appSecret = $this->config->item ( 'AppSecret' );
			FacebookSession::setDefaultApplication ( $appId, $appSecret );
			
			// If you're making app-level requests:
			$session = FacebookSession::newAppSession ();
			// To validate the session:
			try {
				$session->validate ();
				$session = new FacebookSession ( $_SESSION ['access_token'] );
				// var_dump ( $session );
				// create array of tag_uid
				$tagIdList = (isset ( $_POST ["tagIdList"] )) ? $_POST ["tagIdList"] : "";
				$idArray = preg_split ( "/[,]/", $tagIdList );
				$tagData = array ();
				for($i = 0; $i < sizeof ( $idArray ); $i ++) {
					$tagData [$i] = array (
							'tag_uid' => $idArray [$i],
							'x' => 50,
							'y' => 30 
					);
				}
				// Post to facebook
				// Count number of tag friends
				$tagNum = count ( $tagData );
				if ($tagIdList != "")
					switch ($_SESSION ["privacyValue"]) {
						case "EVERYONE" :
							$response = (new FacebookRequest ( $session, 'POST', '/me/photos', array (
									'url' => $imagePath,
									'message' => $message,
									'tags' => json_encode ( $tagData ),
									'privacy' => json_encode ( array (
											'value' => $_SESSION ["privacyValue"] 
									) ) 
							) ))->execute ()->getGraphObject ();
							$this->load->Model ( "muser" );
							$time = date ( 'Y-m-d H:i:s' );
							$this->muser->savePostPrivacy ( $userId, $time, $funcType, $_SESSION ["privacyValue"], $tagNum );
							break;
						case "ALL_FRIENDS" :
							$response = (new FacebookRequest ( $session, 'POST', '/me/photos', array (
									'url' => $imagePath,
									'message' => $message,
									'tags' => json_encode ( $tagData ),
									'privacy' => json_encode ( array (
											'value' => $_SESSION ["privacyValue"] 
									) ) 
							) ))->execute ()->getGraphObject ();
							$this->load->Model ( "muser" );
							$time = date ( 'Y-m-d H:i:s' );
							$this->muser->savePostPrivacy ( $userId, $time, $funcType, $_SESSION ["privacyValue"], $tagNum );
							break;
						case "SELF" :
						default :
							$response = (new FacebookRequest ( $session, 'POST', '/me/photos', array (
									'url' => $imagePath,
									'message' => $message,
									'tags' => json_encode ( $tagData ),
									'privacy' => json_encode ( array (
											'value' => $_SESSION ["privacyValue"] 
									) ) 
							) ))->execute ()->getGraphObject ();
							$this->load->Model ( "muser" );
							$time = date ( 'Y-m-d H:i:s' );
							$this->muser->savePostPrivacy ( $userId, $time, $funcType, $_SESSION ["privacyValue"], $tagNum );
							break;
					}
				else
					switch ($_SESSION ["privacyValue"]) {
						case "EVERYONE" :
							$response = (new FacebookRequest ( $session, 'POST', '/me/photos', array (
									'url' => $imagePath,
									'message' => $message,
									'privacy' => json_encode ( array (
											'value' => $_SESSION ["privacyValue"] 
									) ) 
							) ))->execute ()->getGraphObject ();
							$this->load->Model ( "muser" );
							$time = date ( 'Y-m-d H:i:s' );
							$this->muser->savePostPrivacy ( $userId, $time, $funcType, $_SESSION ["privacyValue"], $tagNum );
							break;
						case "ALL_FRIENDS" :
							$response = (new FacebookRequest ( $session, 'POST', '/me/photos', array (
									'url' => $imagePath,
									'message' => $message,
									'privacy' => json_encode ( array (
											'value' => $_SESSION ["privacyValue"] 
									) ) 
							) ))->execute ()->getGraphObject ();
							$this->load->Model ( "muser" );
							$time = date ( 'Y-m-d H:i:s' );
							$this->muser->savePostPrivacy ( $userId, $time, $funcType, $_SESSION ["privacyValue"], $tagNum );
							break;
						case "SELF" :
						default :
							$response = (new FacebookRequest ( $session, 'POST', '/me/photos', array (
									'url' => $imagePath,
									'message' => $message,
									'privacy' => json_encode ( array (
											'value' => $_SESSION ["privacyValue"] 
									) ) 
							) ))->execute ()->getGraphObject ();
							$this->load->Model ( "muser" );
							$time = date ( 'Y-m-d H:i:s' );
							$this->muser->savePostPrivacy ( $userId, $time, $funcType, $_SESSION ["privacyValue"], $tagNum );
							break;
					}
				
				redirect ( base_url ( "/index.php/ImageUpload/ImageUpload/index" ) );
			} catch ( FacebookRequestException $ex ) {
				// Session not valid, Graph API returned an exception with the reason.
				echo "FacebookRequestException " . $ex->getMessage ();
			} catch ( \Exception $ex ) {
				// Graph API returned info, but it may mismatch the current app or have expired.
				echo "OtherException " . $ex->getMessage ();
			}
		}
	}
}